package com.peng.leetcode.tree;

/**
 * DeleteNode1
 * 450. 删除二叉搜索树中的节点
 * https://leetcode.cn/problems/delete-node-in-a-bst/
 * <p>
 * Created on 2022/11/27
 *
 * @author lupeng
 */
public class DeleteNode1 {

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            // 右子树的最左节点，删除
            if (root.left == null && root.right == null) {
                return null;
            }
            if (root.right == null) {
                return root.left;
            }
            if (root.left == null) {
                return root.right;
            }
            TreeNode c = root.right;
            while (c.left != null) {
                c = c.left;
            }
            root.right = deleteNode(root.right, c.val);
            c.left = root.left;
            c.right = root.right;
            return c;
        }
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }
}
